package controller;

import gui.components.ClientListPanel;

import java.util.Observable;
import java.util.Observer;

import network.Client;
import network.server.ClientList;
import data.UserList;

/**
 * User list controller controls the user list view on the user interface.
 * @author Jie Zhao(288654)
 *
 */
public class UserListController implements Observer {

	private static UserListController instance = null;
	private UserList data = UserList.getInstance();
	private ClientListPanel ui = null;

	private UserListController() {
		data.addObserver(this);
	}
/**
 * 
 * @return an instance of this controller
 */
	public static UserListController getInstance() {
		if (instance == null) {
			instance = new UserListController();
		}
		return instance;
	}
	@Override
	/**
	 * Model updated, update ui
	 */
	public void update(Observable o, Object arg) {
		ui.update(data.getClientList());
	}
/**
 * Kick a user from the server.
 * @param username
 */
	public void kickUser(String username) {
		
		ClientList cl = ClientList.getInstance();
		if (Constants.DEBUG)
			System.out.println("Kicking user:" + username);
		Client c = cl.searchClient(username);
		try {
			c.getClientSocket().close();
		} catch (Exception e) {
		}
		cl.removeClient(c);
		data.removeClient(username);
	}

	/**
	 * 
	 * @param ui
	 */
	public void setUi(ClientListPanel ui) {
		this.ui = ui;
	}
	/**
	 * clear user list
	 */
	public void clear()
	{
		data.clear();
	}
}
